package main

import (
	"image/color"
	"math/rand"
	"time"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"
	themex "github.com/zhaocy/fyne-theme"
)

func main() {
	myApp := app.New()
	myApp.Settings().SetTheme(themex.Themex())
	myWin := myApp.NewWindow("Line")

	line := canvas.NewLine(color.RGBA{255, 0, 0, 255})
	// 左上起始位置
	line.Position1 = fyne.NewPos(30, 30)
	// 右下起始位置
	line.Position2 = fyne.NewPos(100, 30)
	// 宽度
	line.StrokeWidth = 2

	// myWin.SetContent(container.NewWithoutLayout(line))

	zft(myWin)
	myWin.Resize(fyne.NewSize(550, 450))
	myWin.ShowAndRun()
}

// 直方图
func zft(w fyne.Window) {
	data := genData(10, 100)
	c := container.NewWithoutLayout()

	for i, d := range data {
		line := canvas.NewLine(randColor())
		line.Position1 = fyne.NewPos(float32(i*20), 0)
		line.Position2 = fyne.NewPos(float32(i*20), d)
		line.StrokeWidth = 10
		c.Objects = append(c.Objects, line)
	}
	zftBtn := widget.NewButton("开始刷新", nil)
	interval := time.Millisecond * 500
	timer := time.NewTimer(interval)

	zftBtn.OnTapped = func() {
		zft(w)
		for {
			timer.Reset(interval)
			<-timer.C
			zft(w)
		}
	}
	zftBtn.Resize(fyne.NewSize(70, 30))
	zftBtn.Move(fyne.NewPos(0, 100))
	w.SetContent(container.NewVBox(c,
		container.NewWithoutLayout(zftBtn)))
}

func randColor() color.Color {
	return color.RGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)), uint8(rand.Intn(256)), 255}
}

func genData(count, max int) (data []float32) {
	for i := 0; i < count; i++ {
		data = append(data, float32(rand.Intn(max)))
	}
	return
}
